#!/bin/sh

#需要外部传入的参数 todo 看看还有别的办法没（groovy里可以直接调用shell的，看看能不能封装下，shell命令中参数拼装有点恶心）
#shell脚本可以作为template，通过ansible template模块来推到目标机器，并将参数直接写入文件，不需要接到后面来传了
cmd={{action}}
base={{base_path}}
name={{jar_name}}
server_port={{server_port}}
admin_port={{admin_port}}
env={{run_env}}
jvm_param='{{jvm_param}}'
spring_param='{{spring_param}}'

#后面的不需要改动
JENKINS_NODE_COOKIE=dontKillMe
new=$base/next/$name
jar=$base/$name
log_path=$base/logs
time=`date +%F-%H-%M-%S`

back () {
[ -f $jar ] && mv $jar $base/back/${name}_${time} || :
echo 'back'
}

stop () {
#之前是通过输入的端口号来杀进程，遇到需要换端口号的场景就不适用了
#先换成按jar包绝对路径来杀
#todo 后续要换成curl请求对应web项目Actuator的平滑shutdown url来关闭
pid=$(ps -ef | grep  $base/$name|grep -v grep|awk '{print $2}')
if [ ! $pid ]; then
  echo "$name is not running"
else
  echo "$name is running, stop..."
  kill $pid
fi
echo 'stop'

#a=`ss -ant|grep $server_port|wc -l`
#if [ a != 0 ];then
#  echo "$name is running, stop it..."
#  kill $(lsof -t -i:$server_port)
#else
#  echo "$name is not running."
#  :
#fi
#echo 'stop'
}

move () {
mv $new $base
echo 'move'
}

start () {
nohup java $jvm_param -jar $jar --spring.profiles.active=$env >/dev/null --server.port=$server_port --logging.path=$log_path --management.server.port=$admin_port $spring_param 2>&1 &
echo "wait 20s for ${name} starting"
sleep 20
echo "${name} started."
}

rollback () {
mv $jar $new
old_jar=$(ls $base/back -t|head -1)
mv $base/back/$old_jar $base/$name
echo 'roll back'
:
}

case $cmd in
    deploy)
           stop
           back
           move
           start
           ;;
    rollback)
           stop
           rollback
           start
           ;;
    stop)
           stop
           ;;
    start)
           start
           ;;
    restart)
           stop
           start
           ;;
     *)
           echo $"Usage: $0 {deploy|rollback|stop|start|restart}"
           exit
esac